package com.example.cmh.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Logger;

@Configuration
public class DatabaseConfig {
    
    private static final Logger log = Logger.getLogger(DatabaseConfig.class.getName());
    
    @Autowired
    private DataSource dataSource;
    
    @Bean
    public CommandLineRunner checkDatabaseConnection() {
        return args -> {
            log.info("正在检查数据库连接...");
            try (Connection connection = dataSource.getConnection()) {
                log.info("数据库连接成功！");
                log.info("数据库类型: " + connection.getMetaData().getDatabaseProductName());
                log.info("数据库版本: " + connection.getMetaData().getDatabaseProductVersion());
            } catch (SQLException e) {
                log.severe("数据库连接失败: " + e.getMessage());
                e.printStackTrace();
            }
        };
    }
    
    @Bean
    public CommandLineRunner checkDatabaseSchema(JdbcTemplate jdbcTemplate) {
        return args -> {
            try {
                log.info("检查会议表是否存在...");
                Integer count = jdbcTemplate.queryForObject(
                        "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'meeting'", 
                        Integer.class);
                
                if (count != null && count > 0) {
                    log.info("会议表已存在");
                } else {
                    log.warning("会议表不存在，请确保已执行schema.sql脚本");
                }
            } catch (Exception e) {
                log.severe("检查数据库表失败: " + e.getMessage());
                e.printStackTrace();
            }
        };
    }
} 